/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "animator_option_napi.h"
#include "napi_utils.h"

namespace ImageKnifePro {
AnimatorOptionNapi::AnimatorOptionNapi(napi_env env, napi_value jsObject)
{
    env_ = env;
    napi_create_reference(env, jsObject, 1, &jsThis_);

    napi_value value;
    if (napi_get_named_property(env, jsObject, "state", &value) == napi_ok) {
        int32_t st = 0;
        napi_get_value_int32(env, value, &st);
        state = static_cast<ArkUI_AnimationStatus>(st);
    }

    if (napi_get_named_property(env, jsObject, "iterations", &value) == napi_ok) {
        napi_get_value_int32(env, value, &iterations);
    }

    if (napi_get_named_property(env, jsObject, "reverse", &value) == napi_ok) {
        napi_get_value_bool(env, value, &reverse);
    }

    auto func = [env, jsObject](const char* property, napi_ref& onLoad) -> bool {
        napi_value value;
        napi_valuetype type;
        if (napi_get_named_property(env, jsObject, property, &value) == napi_ok) {
            napi_typeof(env, value, &type);
            if (type != napi_undefined) {
                napi_create_reference(env, value, 1, &onLoad);
                return true;
            }
        }
        return false;
    };
    if (func("onStart", onStart_)) {
        onStart = [this]() {this->CallJsFunction(onStart_);};
    }
    if (func("onFinish", onFinish_)) {
        onFinish = [this]() {this->CallJsFunction(onFinish_);};
    }
    if (func("onPause", onPause_)) {
        onPause = [this]() {this->CallJsFunction(onPause_);};
    }
    if (func("onCancel", onCancel_)) {
        onCancel = [this]() {this->CallJsFunction(onCancel_);};
    }
    if (func("onRepeat", onRepeat_)) {
        onRepeat = [this]() {this->CallJsFunction(onRepeat_);};
    }
}

void AnimatorOptionNapi::CallJsFunction(napi_ref ref)
{
    napi_value thisValue;
    napi_value jsFunc;
    napi_get_reference_value(env_, jsThis_, &thisValue);
    napi_get_reference_value(env_, ref, &jsFunc);
    napi_call_function(env_, thisValue, jsFunc, 0, nullptr, nullptr);
}

AnimatorOptionNapi::~AnimatorOptionNapi()
{
    NapiUtils::DeleteReferences(env_, {jsThis_, onStart_, onFinish_, onPause_, onCancel_, onRepeat_});
}

}
